/*
 * Copyright (C) 2013 AndXmppSDK Project <hljdrl@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.drl.xmpp.storage.table;

import java.util.Date;

import org.drl.xmpp.Contact;
import org.drl.xmpp.TMessage;
import org.drl.xmpp.UserInfo;
import org.drl.xmpp.storage.AbstractAccountTable;
import org.drl.xmpp.storage.DataBaseManager;
import org.drl.xmpp.util.StringUtils2;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Data;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 聊天-消息表
 * 
 * @author hljdrl@gmail.com
 * 
 */
public final class MessageTable extends AbstractAccountTable {

	private static final class Fields implements AbstractAccountTable.Fields {

		private Fields() {
		}

		public static final String KEY_READ_STATE = "_READ_STATE";
		public static final String SESSION = "_SESSION";
		public static final String PacketID = "_PacketID";
		public static final String KEY_FROM = "_FROM";
		public static final String KEY_TO = "_TO";
		public static final String KEY_TYPE = "_TYPE";
		public static final String KEY_BODY = "_BODY";
		public static final String KEY_TIME = "_TIME";
	}

	public static final String KEYS[] = { Fields._ID, Fields.SESSION,
			Fields.PacketID, Fields.KEY_FROM, Fields.KEY_TO, Fields.KEY_TYPE,
			Fields.KEY_BODY, Fields.KEY_TIME, Fields.KEY_READ_STATE };
	public static final String TABLE_NAME = "_MSG";
	private final DataBaseManager databaseManager;

	private final static MessageTable instance;

	static {
		instance = new MessageTable(DataBaseManager.getInstance());
	}

	public static MessageTable getInstance() {
		return instance;
	}

	public MessageTable(DataBaseManager databaseManager) {
		this.databaseManager = databaseManager;
	}

	@Override
	public void create(SQLiteDatabase db) {
		String sql = "CREATE TABLE " + TABLE_NAME + " (" + Fields._ID
				+ " INTEGER PRIMARY KEY," + Fields.ACCOUNT + " TEXT,"
				+ Fields.SESSION + " TEXT," + Fields.PacketID + " TEXT,"
				+ Fields.KEY_FROM + " TEXT," +  Fields.KEY_TYPE + " TEXT,"
				+ Fields.KEY_TO + " TEXT," + Fields.KEY_BODY + " TEXT,"
				+ Fields.KEY_TIME + " TEXT," + Fields.KEY_READ_STATE
				+ " INTEGER);";
		DataBaseManager.execSQL(db, sql);
	}
	public static final TMessage readLineTMessage(Cursor c){
		if(c==null)return null;
		TMessage mTm = null ;
		int idIx = c.getColumnIndex(Fields._ID);
		int fmIx = c.getColumnIndex(Fields.KEY_FROM);
		int toIx = c.getColumnIndex(Fields.KEY_TO);
		int byIx = c.getColumnIndex(Fields.KEY_BODY);
		int pdIx = c.getColumnIndex(Fields.PacketID);
		int teIx = c.getColumnIndex(Fields.KEY_TIME);
		int rdIx = c.getColumnIndex(Fields.KEY_READ_STATE);
		//
		mTm = new TMessage(c.getString(toIx));
		mTm.id =c.getLong(idIx);
		mTm.setFrom(c.getString(fmIx));
		mTm.setTo(c.getString(toIx));
		mTm.setBody(c.getString(byIx));
		mTm.setPacketID(c.getString(pdIx));
		try{
		long curTime = Long.parseLong(c.getString(teIx));
		Date time = new Date(curTime);
		mTm.setTimestamp(time);
		}catch(NumberFormatException ne){
			ne.printStackTrace();
		}
		mTm.setRead(c.getInt(rdIx)!=0);
		return mTm;
	}

	public final long write(TMessage msg, UserInfo user) {
		if (msg == null)
			return -1;

		ContentValues values = new ContentValues();
		values.put(Fields.ACCOUNT, StringUtils2.parseName(user.getJid()));
		values.put(Fields.KEY_FROM, msg.getFrom());
		values.put(Fields.KEY_BODY, msg.getBody());
		values.put(Fields.KEY_TO, msg.getTo());
		values.put(Fields.KEY_TIME, msg.getTimestamp().getTime());
		values.put(Fields.KEY_READ_STATE, msg.isRead() ? 0 : 1);
		values.put(Fields.PacketID, msg.getPacketID());
		String to = StringUtils2.parseName(msg.getTo());
		String form = StringUtils2.parseName(msg.getFrom());
		String key = StringUtils2.parseName(user.getJid());
		
		if(form==null)
			form = user.getJid();
		
		if (key.equals(to)) {
			// 接收消息
			values.put(Fields.SESSION, StringUtils2.parseName(form));
		} else if (key.equals(form)) {
			// 发送消息
			values.put(Fields.SESSION, StringUtils2.parseName(to));
		}

		//
		SQLiteDatabase db = databaseManager.getWritableDatabase();
		if (msg.id == null) {
			Cursor c = db.query(getTableName(), getProjection(),
					Fields.PacketID + " = ?",
					new String[] { msg.getPacketID() }, null, null,
					getListOrder());
			if (hasData(c)) {
				msg.id = (long) db.update(TABLE_NAME, values, Fields.PacketID
						+ " = ?", new String[] { msg.getPacketID() });
			} else {
				msg.id =  db.insert(TABLE_NAME, Fields.ACCOUNT, values);
			}
			closeCurosr(c);
		} else {
			msg.id = (long) db.update(TABLE_NAME, values, Fields._ID + " = ?",
					new String[] { String.valueOf(msg.id) });
		}
		DataBaseManager.notifyTableDataChage(this, true);
		return msg.id;
	}
	
	

	public Cursor readChatMessages(UserInfo user,Contact session){
		Cursor mCm = null;
		SQLiteDatabase db = databaseManager.getWritableDatabase();
		String k1 = StringUtils2.parseName(user.getJid());
		String k2 = StringUtils2.parseName(session.getJID());
		mCm = db.query(TABLE_NAME, KEYS, Fields.ACCOUNT+"=? AND "+Fields.SESSION +"=? ", new String[]{k1,k2},
				null, null," _id  asc");
		return mCm;
	}

	@Override
	protected String getTableName() {
		return TABLE_NAME;
	}

	@Override
	protected String[] getProjection() {
		return KEYS;
	}

}
